<template>
  <div class="designer-main">
    <div class="designer-toolbar">
      <div class="toolbar-left">
        <el-button
          @click="$emit('undoAction')"
          :disabled="!canUndo"
          size="small"
          circle
        >
          <el-icon><component :is="markRaw(ArrowLeft)" /></el-icon>
        </el-button>
        <el-button
          @click="$emit('redoAction')"
          :disabled="!canRedo"
          size="small"
          circle
        >
          <el-icon><component :is="markRaw(ArrowRight)" /></el-icon>
        </el-button>
      </div>
      <div class="toolbar-right">
        <el-button @click="$emit('importForm')" size="small">
          <el-icon><component :is="markRaw(Upload)" /></el-icon>
          {{ t("formDesigner.designCanvas.toolbar.import") }}
        </el-button>
        <el-button @click="$emit('exportForm')" size="small">
          <el-icon><component :is="markRaw(Download)" /></el-icon>
          {{ t("formDesigner.designCanvas.toolbar.export") }}
        </el-button>

        <el-button @click="$emit('generateCode')" size="small">{{
          t("formDesigner.designCanvas.toolbar.generateCode")
        }}</el-button>
        <el-button
          @click="$emit('clearForm')"
          plain
          type="danger"
          size="small"
          >{{ t("formDesigner.designCanvas.toolbar.clear") }}</el-button
        >
        <el-button @click="$emit('previewForm')" type="primary" size="small">{{
          t("formDesigner.designCanvas.toolbar.preview")
        }}</el-button>
        <el-button @click="$emit('saveForm')" type="primary" size="small">{{
          t("common.save")
        }}</el-button>
      </div>
    </div>

    <div
      class="form-canvas"
      @drop="handleCanvasDrop"
      @dragover="handleCanvasDragOver"
      @dragenter="handleDragEnter"
      @dragleave="handleCanvasDragLeave"
    >
      <el-form
        ref="formRef"
        :model="formModel"
        :rules="formRules"
        :label-width="formConfig.labelWidth"
        :label-position="formConfig.labelPosition"
        :size="formConfig.size"
      >
        <template v-for="(item, index) in formItems" :key="item.key">
          <!-- 拖拽插入指示器 -->
          <div
            v-if="showInsertIndicator(index, 'before') && !isGridInternalDrag"
            class="drag-insert-indicator"
          ></div>

          <!-- 栅格布局 -->
          <div
            v-if="item.type === 'grid'"
            class="form-item-wrapper grid-wrapper"
            :class="{ active: selectedIndex === index }"
            @click="$emit('selectItem', index)"
            draggable="true"
            @dragstart="handleItemDragStart($event, index)"
            @dragend="handleItemDragEnd"
            @dragover="handleItemDragOver($event, index)"
            @drop="handleItemDrop($event, index)"
          >
            <div class="grid-layout">
              <el-row :gutter="item.gutter || 0">
                <el-col
                  v-for="(col, colIndex) in item.columns"
                  :key="colIndex"
                  :span="col.span"
                  class="grid-column"
                  :class="{
                    'grid-column-active':
                      props.selectedGridColumn === `${index}-${colIndex}`,
                  }"
                  @click.stop="selectGridColumn(index, colIndex)"
                >
                  <div class="grid-column-content">
                    <div class="grid-column-header">
                      <div class="grid-column-actions">
                        <el-button
                          size="small"
                          circle
                          @click.stop="addGridColumn(index)"
                          :title="t('formDesigner.designCanvas.grid.addColumn')"
                        >
                          <el-icon><component :is="markRaw(Plus)" /></el-icon>
                        </el-button>
                        <el-button
                          v-if="item.columns.length > 1"
                          size="small"
                          circle
                          type="danger"
                          @click.stop="removeGridColumn(index, colIndex)"
                          :title="
                            t('formDesigner.designCanvas.grid.deleteColumn')
                          "
                          class="grid-delete-btn"
                        >
                          <el-icon><component :is="markRaw(Minus)" /></el-icon>
                        </el-button>
                      </div>
                    </div>

                    <!-- 栅格内容区域 -->
                    <div
                      class="grid-column-drop-zone"
                      @drop="handleGridColumnDrop($event, index, colIndex)"
                      @dragover="
                        handleGridColumnDragOver($event, index, colIndex)
                      "
                      @dragenter="handleDragEnter"
                      @dragleave="handleGridColumnDragLeave"
                    >
                      <template v-if="col.children && col.children.length > 0">
                        <div
                          v-for="(childItem, childIndex) in col.children"
                          :key="childItem.key"
                          class="grid-child-item"
                          :class="{
                            active:
                              selectedIndex ===
                              `${index}-${colIndex}-${childIndex}`,
                          }"
                          @click.stop="
                            $emit(
                              'selectItem',
                              `${index}-${colIndex}-${childIndex}`
                            )
                          "
                        >
                          <!-- 这里渲染子组件，复用上面的组件渲染逻辑 -->
                          <el-form-item
                            :label="childItem.label"
                            :label-width="childItem.labelWidth"
                            :prop="childItem.field"
                            :required="childItem.required"
                          >
                            <!-- 输入框 -->
                            <el-input
                              v-if="childItem.type === 'input'"
                              v-model="formModel[childItem.field]"
                              :placeholder="childItem.placeholder"
                              :disabled="childItem.disabled"
                              :clearable="childItem.clearable"
                              :maxlength="childItem.maxlength"
                              :type="childItem.inputType"
                              :show-word-limit="childItem.showWordLimit"
                            />

                            <!-- 数字输入框 -->
                            <el-input-number
                              v-else-if="childItem.type === 'number'"
                              v-model="formModel[childItem.field]"
                              :placeholder="childItem.placeholder"
                              :min="childItem.min"
                              :max="childItem.max"
                              :step="childItem.step"
                              :precision="childItem.precision"
                              :step-strictly="childItem.stepStrictly"
                              :controls-position="childItem.controlsPosition"
                              :disabled="childItem.disabled"
                            />

                            <!-- 选择器 -->
                            <el-select
                              v-else-if="childItem.type === 'select'"
                              v-model="formModel[childItem.field]"
                              :placeholder="childItem.placeholder"
                              :disabled="childItem.disabled"
                              :clearable="childItem.clearable"
                              :multiple="childItem.multiple"
                              :filterable="childItem.filterable"
                              :collapse-tags="childItem.collapseTags"
                              :max-collapse-tags="childItem.maxCollapseTags"
                              :multiple-limit="childItem.multipleLimit || 0"
                            >
                              <el-option
                                v-for="option in childItem.options"
                                :key="option.value"
                                :label="option.label"
                                :value="option.value"
                              />
                            </el-select>

                            <!-- 单选框组 -->
                            <el-radio-group
                              v-else-if="childItem.type === 'radio'"
                              v-model="formModel[childItem.field]"
                              :disabled="childItem.disabled"
                            >
                              <template v-if="childItem.buttonStyle">
                                <el-radio-button
                                  v-for="option in childItem.options"
                                  :key="option.value"
                                  :value="option.value"
                                >
                                  {{ option.label }}
                                </el-radio-button>
                              </template>
                              <template v-else>
                                <el-radio
                                  v-for="option in childItem.options"
                                  :key="option.value"
                                  :value="option.value"
                                  :border="childItem.border"
                                >
                                  {{ option.label }}
                                </el-radio>
                              </template>
                            </el-radio-group>

                            <!-- 多选框组 -->
                            <el-checkbox-group
                              v-else-if="childItem.type === 'checkbox'"
                              v-model="formModel[childItem.field]"
                              :disabled="childItem.disabled"
                              :min="childItem.min"
                              :max="childItem.max"
                            >
                              <template v-if="childItem.buttonStyle">
                                <el-checkbox-button
                                  v-for="option in childItem.options"
                                  :key="option.value"
                                  :value="option.value"
                                >
                                  {{ option.label }}
                                </el-checkbox-button>
                              </template>
                              <template v-else>
                                <el-checkbox
                                  v-for="option in childItem.options"
                                  :key="option.value"
                                  :value="option.value"
                                  :border="childItem.border"
                                >
                                  {{ option.label }}
                                </el-checkbox>
                              </template>
                            </el-checkbox-group>

                            <!-- 日期选择器 -->
                            <el-date-picker
                              v-else-if="childItem.type === 'date'"
                              v-model="formModel[childItem.field]"
                              :type="childItem.dateType"
                              :placeholder="childItem.placeholder"
                              :disabled="childItem.disabled"
                              :clearable="childItem.clearable"
                            />

                            <!-- 时间选择器 -->
                            <el-time-picker
                              v-else-if="childItem.type === 'time'"
                              v-model="formModel[childItem.field]"
                              :placeholder="childItem.placeholder"
                              :disabled="childItem.disabled"
                              :clearable="childItem.clearable"
                              :format="childItem.format"
                            />

                            <!-- 开关 -->
                            <el-switch
                              v-else-if="childItem.type === 'switch'"
                              v-model="formModel[childItem.field]"
                              :disabled="childItem.disabled"
                              :active-text="childItem.activeText"
                              :inactive-text="childItem.inactiveText"
                            />

                            <!-- 文本域 -->
                            <el-input
                              v-else-if="childItem.type === 'textarea'"
                              v-model="formModel[childItem.field]"
                              type="textarea"
                              :placeholder="childItem.placeholder"
                              :disabled="childItem.disabled"
                              :rows="childItem.rows"
                              :autosize="childItem.autosize || false"
                            />

                            <!-- 树形控件 -->
                            <el-tree
                              v-else-if="childItem.type === 'tree'"
                              :data="childItem.data || []"
                              :props="
                                childItem.props || {
                                  children: 'children',
                                  label: 'label',
                                }
                              "
                              :show-checkbox="childItem.showCheckbox"
                              :check-strictly="childItem.checkStrictly"
                              :default-expand-all="childItem.defaultExpandAll"
                              :expand-on-click-node="
                                childItem.expandOnClickNode
                              "
                              :check-on-click-node="childItem.checkOnClickNode"
                              :default-expanded-keys="
                                childItem.defaultExpandedKeys || []
                              "
                              :default-checked-keys="
                                childItem.defaultCheckedKeys || []
                              "
                              :node-key="childItem.nodeKey || 'id'"
                              :accordion="childItem.accordion"
                              :indent="childItem.indent || 18"
                              :icon="childItem.icon"
                              :lazy="childItem.lazy"
                              :load="childItem.load"
                              :draggable="childItem.draggable"
                              :allow-drag="childItem.allowDrag"
                              :allow-drop="childItem.allowDrop"
                              :filter-node-method="childItem.filterNodeMethod"
                              :render-after-expand="childItem.renderAfterExpand"
                              :render-content="childItem.renderContent"
                            />

                            <!-- 树形选择器 -->
                            <el-tree-select
                              v-else-if="childItem.type === 'treeselect'"
                              v-model="formModel[childItem.field]"
                              :data="childItem.data || []"
                              :props="
                                childItem.props || {
                                  children: 'children',
                                  label: 'label',
                                  value: 'value',
                                }
                              "
                              :placeholder="childItem.placeholder"
                              :disabled="childItem.disabled"
                              :clearable="childItem.clearable"
                              :multiple="childItem.multiple"
                              :collapse-tags="childItem.collapseTags"
                              :collapse-tags-tooltip="
                                childItem.collapseTagsTooltip
                              "
                              :max-collapse-tags="childItem.maxCollapseTags"
                              :filterable="childItem.filterable"
                              :filter-method="childItem.filterMethod"
                              :remote="childItem.remote"
                              :remote-method="childItem.remoteMethod"
                              :loading="childItem.loading"
                              :no-data-text="childItem.noDataText"
                              :no-match-text="childItem.noMatchText"
                              :loading-text="childItem.loadingText"
                              :popper-class="childItem.popperClass"
                              :teleported="childItem.teleported"
                              :persistent="childItem.persistent"
                              :automatic-dropdown="childItem.automaticDropdown"
                              :size="childItem.size"
                              :effect="childItem.effect"
                              :placement="childItem.placement"
                              :fallback-placements="
                                childItem.fallbackPlacements
                              "
                              :popper-options="childItem.popperOptions"
                              :show-checkbox="childItem.showCheckbox"
                              :check-strictly="childItem.checkStrictly"
                              :check-on-click-node="childItem.checkOnClickNode"
                              :expand-on-click-node="
                                childItem.expandOnClickNode
                              "
                              :default-expand-all="childItem.defaultExpandAll"
                              :default-expanded-keys="
                                childItem.defaultExpandedKeys || []
                              "
                              :node-key="childItem.nodeKey || 'id'"
                              :render-after-expand="childItem.renderAfterExpand"
                              :load="childItem.load"
                              :render-content="childItem.renderContent"
                              :lazy="childItem.lazy"
                              :indent="childItem.indent || 16"
                              :icon="childItem.icon"
                              :accordion="childItem.accordion"
                            />

                            <!-- 级联选择器 -->
                            <el-cascader
                              v-else-if="childItem.type === 'cascader'"
                              v-model="formModel[childItem.field]"
                              :options="childItem.options || []"
                              :placeholder="childItem.placeholder"
                              :disabled="childItem.disabled"
                              :clearable="
                                childItem.clearable !== undefined
                                  ? childItem.clearable
                                  : true
                              "
                              :filterable="
                                childItem.filterable !== undefined
                                  ? childItem.filterable
                                  : false
                              "
                              :collapse-tags="
                                childItem.collapseTags !== undefined
                                  ? childItem.collapseTags
                                  : false
                              "
                              :separator="childItem.separator || ' / '"
                              :show-all-levels="
                                childItem.showAllLevels !== undefined
                                  ? childItem.showAllLevels
                                  : true
                              "
                              :props="{
                                multiple:
                                  childItem.multiple !== undefined
                                    ? childItem.multiple
                                    : false,
                                expandTrigger:
                                  childItem.expandTrigger || 'click',
                                checkStrictly:
                                  childItem.checkStrictly !== undefined
                                    ? childItem.checkStrictly
                                    : false,
                              }"
                            />

                            <!-- 滑块 -->
                            <el-slider
                              v-else-if="childItem.type === 'slider'"
                              v-model="formModel[childItem.field]"
                              :min="childItem.min || 0"
                              :max="childItem.max || 100"
                              :step="childItem.step || 1"
                              :disabled="childItem.disabled || false"
                              :show-input="childItem.showInput || false"
                              :show-input-controls="
                                childItem.showInputControls !== false
                              "
                              :show-stops="childItem.showStops || false"
                              :show-tooltip="childItem.showTooltip !== false"
                              :format-tooltip="childItem.formatTooltip"
                              :range="childItem.range || false"
                              :vertical="childItem.vertical || false"
                              :height="
                                childItem.vertical
                                  ? childItem.height || '200px'
                                  : undefined
                              "
                              :marks="childItem.marks"
                            />
                          </el-form-item>

                          <!-- 子组件操作按钮 -->
                          <div
                            class="child-item-actions"
                            v-if="
                              selectedIndex ===
                              `${index}-${colIndex}-${childIndex}`
                            "
                          >
                            <el-button
                              type="danger"
                              size="small"
                              :icon="markRaw(Delete)"
                              circle
                              @click.stop="
                                removeGridChildItem(index, colIndex, childIndex)
                              "
                            />
                          </div>
                        </div>
                      </template>
                      <div v-else class="grid-column-empty">
                        <el-empty
                          :description="
                            t('formDesigner.designCanvas.empty.dragHere')
                          "
                          :image-size="40"
                        />
                      </div>
                    </div>
                  </div>
                </el-col>
              </el-row>
            </div>
          </div>

          <!-- 描述列表 -->
          <div
            v-else-if="item.type === 'descriptions'"
            class="form-item-wrapper descriptions-wrapper"
            :class="{ active: selectedIndex === index }"
            @click="$emit('selectItem', index)"
            draggable="true"
            @dragstart="handleItemDragStart($event, index)"
            @dragend="handleItemDragEnd"
            @dragover="handleItemDragOver($event, index)"
            @drop="handleItemDrop($event, index)"
          >
            <el-descriptions
              :title="item.title"
              :column="item.column || 3"
              :size="item.size"
              :border="item.border || false"
              :direction="item.direction || 'horizontal'"
              :extra="item.extra"
            >
              <el-descriptions-item
                v-for="(descItem, descIndex) in item.items || []"
                :key="descIndex"
                :label="descItem.label"
                :span="descItem.span || 1"
                :width="descItem.width"
                :min-width="descItem.minWidth"
                :align="descItem.align"
                :label-align="descItem.labelAlign"
                :class-name="descItem.className"
                :label-class-name="descItem.labelClassName"
              >
                {{ descItem.value }}
              </el-descriptions-item>
            </el-descriptions>
          </div>

          <!-- 其他表单组件 -->
          <div
            v-else
            class="form-item-wrapper"
            :class="{ active: selectedIndex === index }"
            @click="$emit('selectItem', index)"
            draggable="true"
            @dragstart="handleItemDragStart($event, index)"
            @dragend="handleItemDragEnd"
            @dragover="handleItemDragOver($event, index)"
            @drop="handleItemDrop($event, index)"
          >
            <el-form-item
              :label="item.label"
              :label-width="item.labelWidth"
              :prop="item.field"
              :required="item.required"
            >
              <!-- 输入框 -->
              <el-input
                v-if="item.type === 'input'"
                v-model="formModel[item.field]"
                :placeholder="item.placeholder"
                :disabled="item.disabled"
                :clearable="item.clearable"
                :maxlength="item.maxlength"
                :type="item.inputType"
                :show-word-limit="item.showWordLimit"
              />

              <!-- 数字输入框 -->
              <el-input-number
                v-else-if="item.type === 'number'"
                v-model="formModel[item.field]"
                :placeholder="item.placeholder"
                :min="item.min"
                :max="item.max"
                :step="item.step"
                :precision="item.precision"
                :step-strictly="item.stepStrictly"
                :controls-position="item.controlsPosition"
                :disabled="item.disabled"
              />

              <!-- 选择器 -->
              <el-select
                v-else-if="item.type === 'select'"
                v-model="formModel[item.field]"
                :placeholder="item.placeholder"
                :disabled="item.disabled"
                :clearable="item.clearable"
                :multiple="item.multiple"
                :filterable="item.filterable"
                :collapse-tags="item.collapseTags"
                :max-collapse-tags="item.maxCollapseTags"
                :multiple-limit="item.multipleLimit || 0"
              >
                <el-option
                  v-for="option in item.options"
                  :key="option.value"
                  :label="option.label"
                  :value="option.value"
                />
              </el-select>

              <!-- 单选框组 -->
              <el-radio-group
                v-else-if="item.type === 'radio'"
                v-model="formModel[item.field]"
                :disabled="item.disabled"
              >
                <template v-if="item.buttonStyle">
                  <el-radio-button
                    v-for="option in item.options"
                    :key="option.value"
                    :value="option.value"
                  >
                    {{ option.label }}
                  </el-radio-button>
                </template>
                <template v-else>
                  <el-radio
                    v-for="option in item.options"
                    :key="option.value"
                    :value="option.value"
                    :border="item.border"
                  >
                    {{ option.label }}
                  </el-radio>
                </template>
              </el-radio-group>

              <!-- 多选框组 -->
              <el-checkbox-group
                v-else-if="item.type === 'checkbox'"
                v-model="formModel[item.field]"
                :disabled="item.disabled"
                :min="item.min"
                :max="item.max"
              >
                <template v-if="item.buttonStyle">
                  <el-checkbox-button
                    v-for="option in item.options"
                    :key="option.value"
                    :value="option.value"
                  >
                    {{ option.label }}
                  </el-checkbox-button>
                </template>
                <template v-else>
                  <el-checkbox
                    v-for="option in item.options"
                    :key="option.value"
                    :value="option.value"
                    :border="item.border"
                  >
                    {{ option.label }}
                  </el-checkbox>
                </template>
              </el-checkbox-group>

              <!-- 日期选择器 -->
              <el-date-picker
                v-else-if="item.type === 'date'"
                v-model="formModel[item.field]"
                :format="item.format"
                :type="item.dateType"
                :placeholder="item.placeholder"
                :disabled="item.disabled"
                :clearable="item.clearable"
              />

              <!-- 时间选择器 -->
              <el-time-picker
                v-else-if="item.type === 'time'"
                v-model="formModel[item.field]"
                :placeholder="item.placeholder"
                :disabled="item.disabled"
                :clearable="item.clearable"
                :format="item.format"
              />

              <!-- 开关 -->
              <el-switch
                v-else-if="item.type === 'switch'"
                v-model="formModel[item.field]"
                :disabled="item.disabled"
                :active-text="item.activeText"
                :inactive-text="item.inactiveText"
              />

              <!-- 文本域 -->
              <el-input
                v-else-if="item.type === 'textarea'"
                v-model="formModel[item.field]"
                type="textarea"
                :placeholder="item.placeholder"
                :disabled="item.disabled"
                :rows="item.rows"
                :autosize="item.autosize || false"
              />

              <!-- 树形控件 -->
              <el-tree
                v-else-if="item.type === 'tree'"
                :data="item.data || []"
                :props="item.props || { children: 'children', label: 'label' }"
                :show-checkbox="item.showCheckbox"
                :check-strictly="item.checkStrictly"
                :default-expand-all="item.defaultExpandAll"
                :expand-on-click-node="item.expandOnClickNode"
                :check-on-click-node="item.checkOnClickNode"
                :default-expanded-keys="item.defaultExpandedKeys || []"
                :default-checked-keys="item.defaultCheckedKeys || []"
                :node-key="item.nodeKey || 'id'"
                :accordion="item.accordion"
                :indent="item.indent || 18"
                :icon="item.icon"
                :lazy="item.lazy"
                :load="item.load"
                :draggable="item.draggable"
                :allow-drag="item.allowDrag"
                :allow-drop="item.allowDrop"
                :filter-node-method="item.filterNodeMethod"
                :render-after-expand="item.renderAfterExpand"
                :render-content="item.renderContent"
              />

              <!-- 树形选择器 -->
              <el-tree-select
                v-else-if="item.type === 'treeselect'"
                v-model="formModel[item.field]"
                :data="item.data || []"
                :props="
                  item.props || {
                    children: 'children',
                    label: 'label',
                    value: 'value',
                  }
                "
                :placeholder="item.placeholder"
                :disabled="item.disabled"
                :clearable="item.clearable"
                :multiple="item.multiple"
                :collapse-tags="item.collapseTags"
                :collapse-tags-tooltip="item.collapseTagsTooltip"
                :max-collapse-tags="item.maxCollapseTags"
                :filterable="item.filterable"
                :filter-method="item.filterMethod"
                :remote="item.remote"
                :remote-method="item.remoteMethod"
                :loading="item.loading"
                :no-data-text="item.noDataText"
                :no-match-text="item.noMatchText"
                :loading-text="item.loadingText"
                :popper-class="item.popperClass"
                :teleported="item.teleported"
                :persistent="item.persistent"
                :automatic-dropdown="item.automaticDropdown"
                :size="item.size"
                :effect="item.effect"
                :placement="item.placement"
                :fallback-placements="item.fallbackPlacements"
                :popper-options="item.popperOptions"
                :show-checkbox="item.showCheckbox"
                :check-strictly="item.checkStrictly"
                :check-on-click-node="item.checkOnClickNode"
                :expand-on-click-node="item.expandOnClickNode"
                :default-expand-all="item.defaultExpandAll"
                :default-expanded-keys="item.defaultExpandedKeys || []"
                :node-key="item.nodeKey || 'id'"
                :render-after-expand="item.renderAfterExpand"
                :load="item.load"
                :render-content="item.renderContent"
                :lazy="item.lazy"
                :indent="item.indent || 16"
                :icon="item.icon"
                :accordion="item.accordion"
              />

              <!-- 级联选择器 -->
              <el-cascader
                v-else-if="item.type === 'cascader'"
                v-model="formModel[item.field]"
                :options="item.options || []"
                :placeholder="item.placeholder"
                :disabled="item.disabled"
                :clearable="
                  item.clearable !== undefined ? item.clearable : true
                "
                :filterable="
                  item.filterable !== undefined ? item.filterable : false
                "
                :collapse-tags="
                  item.collapseTags !== undefined ? item.collapseTags : false
                "
                :separator="item.separator || ' / '"
                :show-all-levels="
                  item.showAllLevels !== undefined ? item.showAllLevels : true
                "
                :props="{
                  multiple: item.multiple !== undefined ? item.multiple : false,
                  expandTrigger: item.expandTrigger || 'click',
                  checkStrictly:
                    item.checkStrictly !== undefined
                      ? item.checkStrictly
                      : false,
                }"
              />

              <!-- 滑块 -->
              <el-slider
                v-else-if="item.type === 'slider'"
                v-model="formModel[item.field]"
                :min="item.min || 0"
                :max="item.max || 100"
                :step="item.step || 1"
                :disabled="item.disabled || false"
                :show-input="item.showInput || false"
                :show-input-controls="item.showInputControls !== false"
                :show-stops="item.showStops || false"
                :show-tooltip="item.showTooltip !== false"
                :format-tooltip="item.formatTooltip"
                :range="item.range || false"
                :vertical="item.vertical || false"
                :height="item.vertical ? item.height || '200px' : undefined"
                :marks="item.marks"
              />
            </el-form-item>

            <!-- 操作按钮 -->
            <div class="item-actions" v-if="selectedIndex === index">
              <el-button
                type="primary"
                size="small"
                :icon="markRaw(DocumentCopy)"
                circle
                @click.stop="$emit('copyItem', index)"
              />
              <el-button
                type="danger"
                size="small"
                :icon="markRaw(Delete)"
                circle
                @click.stop="$emit('deleteItem', index)"
              />
            </div>
          </div>

          <!-- 拖拽插入指示器 -->
          <div
            v-if="showInsertIndicator(index, 'after') && !isGridInternalDrag"
            class="drag-insert-indicator"
          ></div>
        </template>

        <!-- 空状态或末尾插入指示器 -->
        <div v-if="formItems.length === 0" class="empty-canvas">
          <el-empty
            :description="t('formDesigner.designCanvas.empty.startDesign')"
          />
        </div>
      </el-form>
    </div>
  </div>
</template>

<script setup>
import { ref, markRaw, computed } from "vue";
import { useI18n } from "vue-i18n";
import {
  ArrowLeft,
  ArrowRight,
  DocumentCopy,
  Delete,
  Plus,
  Minus,
  Upload,
  Download,
} from "@element-plus/icons-vue";
import { browse } from "xe-utils";

// 国际化
const { t } = useI18n();

// Props
const props = defineProps({
  formItems: {
    type: Array,
    default: () => [],
  },
  formModel: {
    type: Object,
    default: () => ({}),
  },
  formConfig: {
    type: Object,
    default: () => ({}),
  },
  selectedIndex: {
    type: [Number, String],
    default: -1,
  },
  selectedGridColumn: {
    type: String,
    default: "",
  },
  canUndo: {
    type: Boolean,
    default: false,
  },
  canRedo: {
    type: Boolean,
    default: false,
  },
});

// Emits
const emit = defineEmits([
  "selectItem",
  "selectGridColumn",
  "copyItem",
  "deleteItem",
  "undoAction",
  "redoAction",
  "previewForm",
  "generateCode",
  "clearForm",
  "saveForm",
  "addFormItem",
  "moveFormItem",
  "importForm",
  "exportForm",
]);

// 表单验证规则
const formRules = computed(() => {
  const rules = {};

  const addRules = (items) => {
    items.forEach((item) => {
      if (item.type === "grid") {
        // 处理栅格布局中的子组件
        item.columns?.forEach((column) => {
          if (column.children) {
            addRules(column.children);
          }
        });
      } else if (item.field) {
        const fieldRules = [];

        // 必填验证
        if (item.required) {
          const message = item.requiredMessage || `请输入${item.label}`;
          const trigger = getTriggerByType(item.type);
          const requiredRule = { required: true, message, trigger };

          // 级联选择器在多选模式下需要特殊处理
          if (item.type === "cascader" && item.multiple) {
            requiredRule.type = "array";
            requiredRule.min = 1;
          }

          fieldRules.push(requiredRule);
        }

        // 自定义验证规则
        if (item.validationRules && item.validationRules.length > 0) {
          item.validationRules.forEach((rule) => {
            const validationRule = {
              message: rule.message || "验证失败",
              trigger: rule.trigger || "change",
            };

            switch (rule.type) {
              case "minLength":
                validationRule.min = parseInt(rule.value);
                break;
              case "maxLength":
                validationRule.max = parseInt(rule.value);
                break;
              case "pattern":
                validationRule.pattern = new RegExp(rule.value);
                break;
              case "min":
                validationRule.type = "number";
                validationRule.min = parseFloat(rule.value);
                break;
              case "max":
                validationRule.type = "number";
                validationRule.max = parseFloat(rule.value);
                break;
              case "minItems":
                validationRule.type = "array";
                validationRule.min = parseInt(rule.value);
                break;
              case "maxItems":
                validationRule.type = "array";
                validationRule.max = parseInt(rule.value);
                break;
              case "custom":
                validationRule.validator = (rule, value, callback) => {
                  try {
                    const customValidator = new Function(
                      "rule",
                      "value",
                      "callback",
                      rule.value
                    );
                    customValidator(rule, value, callback);
                  } catch (error) {
                    callback(new Error("验证规则错误"));
                  }
                };
                break;
            }

            fieldRules.push(validationRule);
          });
        }

        if (fieldRules.length > 0) {
          rules[item.field] = fieldRules;
        }
      }
    });
  };

  addRules(props.formItems);
  return rules;
});

// 根据组件类型获取触发时机
const getTriggerByType = (type) => {
  const triggerMap = {
    input: "blur",
    textarea: "blur",
    number: "blur",
    select: "change",
    cascader: "change",
    treeselect: "change",
    radio: "change",
    checkbox: "change",
    date: "change",
    switch: "change",
  };
  return triggerMap[type] || "change";
};

// 拖拽排序相关
const dragIndex = ref(-1);
const dragInsertIndex = ref(-1);
const isGridInternalDrag = ref(false);

// 画布拖拽悬停
const handleCanvasDragOver = (event) => {
  event.preventDefault();

  // 只处理从组件面板拖拽的情况
  if (dragIndex.value === -1) {
    // 检查是否在表单项上
    const formItemWrapper = event.target.closest(".form-item-wrapper");
    if (!formItemWrapper && props.formItems.length > 0) {
      // 在空白区域，插入到末尾
      dragInsertIndex.value = props.formItems.length;
    } else if (props.formItems.length === 0) {
      // 空表单，插入到开头
      dragInsertIndex.value = 0;
    }
  }
};

// 画布拖拽离开
const handleCanvasDragLeave = (event) => {
  // 只有当离开整个画布区域时才清除指示器
  const relatedTarget = event.relatedTarget;
  if (!relatedTarget || !event.currentTarget.contains(relatedTarget)) {
    dragInsertIndex.value = -1;
  }
};

// 处理拖拽进入
const handleDragEnter = (event) => {
  event.preventDefault();
};

// 画布拖拽放置
const handleCanvasDrop = (event) => {
  event.preventDefault();

  const componentData = event.dataTransfer.getData("component");

  if (componentData && dragIndex.value === -1) {
    // 从组件面板拖拽
    const component = JSON.parse(componentData);
    const insertIndex =
      dragInsertIndex.value >= 0
        ? dragInsertIndex.value
        : props.formItems.length;
    emit("addFormItem", component, insertIndex);
  }

  resetDragState();
};

// 重置拖拽状态
const resetDragState = () => {
  dragIndex.value = -1;
  dragInsertIndex.value = -1;
  isGridInternalDrag.value = false;
};

// 显示插入指示器
const showInsertIndicator = (index, position) => {
  if (dragInsertIndex.value === -1) return false;

  // 检查是否是栅格布局且当前正在栅格内部拖拽
  const item = props.formItems[index];
  if (item && item.type === "grid" && isGridInternalDrag.value) {
    return false;
  }

  if (position === "before") {
    return dragInsertIndex.value === index;
  } else {
    return dragInsertIndex.value === index + 1;
  }
};

// 表单项拖拽开始
const handleItemDragStart = (event, index) => {
  dragIndex.value = index;
  event.dataTransfer.effectAllowed = "move";
  event.dataTransfer.setData("item-index", index.toString());
};

// 表单项拖拽结束
const handleItemDragEnd = (event) => {
  resetDragState();
};

// 表单项拖拽悬停
const handleItemDragOver = (event, index) => {
  event.preventDefault();
  event.stopPropagation();

  const rect = event.currentTarget.getBoundingClientRect();
  const relativeY = event.clientY - rect.top;
  const threshold = rect.height * 0.3; // 使用30%作为阈值，而不是50%

  if (dragIndex.value === -1) {
    // 从组件面板拖拽
    if (relativeY < threshold) {
      dragInsertIndex.value = index;
    } else if (relativeY > rect.height - threshold) {
      dragInsertIndex.value = index + 1;
    } else {
      // 在中间区域时，根据拖拽方向决定插入位置
      dragInsertIndex.value = index + 1;
    }
  } else {
    // 表单项排序拖拽
    if (dragIndex.value !== index) {
      if (relativeY < threshold) {
        dragInsertIndex.value = index;
      } else if (relativeY > rect.height - threshold) {
        dragInsertIndex.value = index + 1;
      } else {
        // 在中间区域时，根据拖拽源位置决定插入位置
        if (dragIndex.value < index) {
          dragInsertIndex.value = index + 1;
        } else {
          dragInsertIndex.value = index;
        }
      }
    }
  }
};

// 表单项拖拽放置
const handleItemDrop = (event, index) => {
  event.preventDefault();
  event.stopPropagation();

  const componentData = event.dataTransfer.getData("component");
  const itemIndex = event.dataTransfer.getData("item-index");

  if (componentData && dragIndex.value === -1) {
    // 从组件面板拖拽到表单项
    const component = JSON.parse(componentData);
    const insertIndex =
      dragInsertIndex.value >= 0 ? dragInsertIndex.value : index;
    emit("addFormItem", component, insertIndex);
  } else if (itemIndex !== "" && dragIndex.value >= 0) {
    // 表单项排序拖拽
    const fromIndex = parseInt(itemIndex);
    const toIndex = dragInsertIndex.value >= 0 ? dragInsertIndex.value : index;

    if (fromIndex !== toIndex) {
      emit("moveFormItem", fromIndex, toIndex);
    }
  }

  resetDragState();
};

// 栅格布局相关方法
// 选择栅格列
const selectGridColumn = (gridIndex, colIndex) => {
  emit("selectGridColumn", gridIndex, colIndex);
};

// 添加栅格列
const addGridColumn = (gridIndex) => {
  const gridItem = props.formItems[gridIndex];
  if (gridItem && gridItem.type === "grid") {
    const newColumn = {
      span: 12,
      children: [],
    };
    gridItem.columns.push(newColumn);
    // 不再限制总和为24，允许自动换行
  }
};

// 删除栅格列
const removeGridColumn = (gridIndex, colIndex) => {
  const gridItem = props.formItems[gridIndex];
  if (gridItem && gridItem.type === "grid" && gridItem.columns.length > 1) {
    gridItem.columns.splice(colIndex, 1);
    // 重新分配列宽
    // redistributeColumnSpans(gridItem.columns);
  }
};

// 更新栅格列宽
const updateGridColumnSpan = (gridIndex, colIndex, newSpan) => {
  const gridItem = props.formItems[gridIndex];
  if (gridItem && gridItem.type === "grid") {
    gridItem.columns[colIndex].span = newSpan;
    // 确保总宽度不超过24
    const totalSpan = gridItem.columns.reduce((sum, col) => sum + col.span, 0);
    if (totalSpan > 24) {
      redistributeColumnSpans(gridItem.columns);
    }
  }
};

// 重新分配列宽
const redistributeColumnSpans = (columns) => {
  const totalColumns = columns.length;
  const spanPerColumn = Math.floor(24 / totalColumns);
  const remainder = 24 % totalColumns;

  columns.forEach((col, index) => {
    col.span = spanPerColumn + (index < remainder ? 1 : 0);
  });
};

// 栅格列拖拽处理
const handleGridColumnDragOver = (event, gridIndex, colIndex) => {
  event.preventDefault();
  event.stopPropagation();
  isGridInternalDrag.value = true;
};

// 将组件拖拽出栅格布局
const handleGridColumnDragLeave = (event) => {
  event.preventDefault();

  // 检查是否真正离开了栅格区域
  const relatedTarget = event.relatedTarget; // 指向鼠标移动到的新元素
  const currentGridColumn = event.currentTarget; // 当前绑定事件的栅格元素：grid-column-drop-zone

  // 如果relatedTarget不存在，或者不在当前栅格列内，才重置状态
  if (!relatedTarget || !currentGridColumn.contains(relatedTarget)) {
    isGridInternalDrag.value = false;
  }
};

const handleGridColumnDrop = (event, gridIndex, colIndex) => {
  event.preventDefault();
  event.stopPropagation();

  const componentData = event.dataTransfer.getData("component");
  if (componentData) {
    const component = JSON.parse(componentData);
    // 不允许在栅格内嵌套栅格
    if (component.type === "grid") {
      return;
    }

    const gridItem = props.formItems[gridIndex];
    if (gridItem && gridItem.type === "grid") {
      const column = gridItem.columns[colIndex];
      if (column) {
        // 创建子组件
        const key = `field_${Date.now()}_${Math.random()
          .toString(36)
          .substr(2, 9)}`;
        const newChildItem = {
          key,
          field: key,
          label: component.label,
          type: component.type,
          placeholder: `请输入${component.label}`,
          required: false,
          disabled: false,
          ...getDefaultGridChildProps(component.type),
        };

        if (!column.children) {
          column.children = [];
        }
        column.children.push(newChildItem);

        // 初始化表单数据
        props.formModel[key] = getDefaultGridChildValue(component.type);
      }
    }
  }

  resetDragState();
};

// 删除栅格子组件
const removeGridChildItem = (gridIndex, colIndex, childIndex) => {
  const gridItem = props.formItems[gridIndex];
  if (gridItem && gridItem.type === "grid") {
    const column = gridItem.columns[colIndex];
    if (column && column.children) {
      const childItem = column.children[childIndex];
      if (childItem) {
        // 删除表单数据
        delete props.formModel[childItem.field];
        // 删除子组件
        column.children.splice(childIndex, 1);
      }
    }
  }
};

// 获取栅格子组件默认属性
const getDefaultGridChildProps = (type) => {
  const props = {};

  switch (type) {
    case "number":
      props.min = 0;
      props.max = 100;
      props.step = 1;
      break;
    case "select":
    case "radio":
    case "checkbox":
      props.options = [
        { label: "选项1", value: "1" },
        { label: "选项2", value: "2" },
      ];
      props.multiple = type === "select" ? false : undefined;
      break;
    case "date":
      props.dateType = "date";
      break;
    case "textarea":
      props.rows = 3;
      break;
    case "input":
      props.clearable = true;
      break;
  }

  return props;
};

// 获取栅格子组件默认值
const getDefaultGridChildValue = (type) => {
  switch (type) {
    case "number":
      return 0;
    case "checkbox":
      return [];
    case "switch":
      return false;
    case "tree":
      return [];
    case "treeselect":
      return "";
    case "cascader":
      return [];
    default:
      return "";
  }
};
</script>

<style lang="less" scoped>
.designer-main {
  flex: 1;
  display: flex;
  flex-direction: column;
  background: var(--el-bg-color);
  margin: 0 1px;
}

.designer-toolbar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px 16px;
  border-bottom: 1px solid var(--el-border-color-lighter);
  background: var(--el-bg-color);
  // box-shadow: var(--el-box-shadow-light);
}

.toolbar-left {
  display: flex;
  gap: 8px;
}

.toolbar-right {
  display: flex;
  gap: 8px;
}

.form-canvas {
  flex: 1;
  padding: 20px;
  overflow-y: auto;
  min-height: 400px;
}

.form-item-wrapper {
  position: relative;
  margin-bottom: 2px;
  padding: 8px;
  border: 2px dashed transparent;
  border-radius: 4px;
  transition: all 0.3s;

  &:hover {
    border-color: var(--el-border-color);
  }

  &.active {
    border-color: var(--el-color-primary);
    background: var(--el-color-primary-light-9);
  }
}

.drag-insert-indicator {
  height: 2px;
  background: var(--el-color-primary);
  margin: 4px 0;
  opacity: 0.8;
}

.item-actions {
  position: absolute;
  bottom: 8px;
  right: 8px;
  display: flex;
  gap: 4px;
  opacity: 0.8;
  backdrop-filter: blur(4px);
  transition: all 0.2s ease;
  z-index: 10;

  &:hover {
    opacity: 1;
    transform: scale(1.05);
  }

  .el-button {
    width: 24px;
    height: 24px;
    padding: 0;
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  }

  .el-button--danger {
    background-color: #fff;
    border-color: #f56c6c;
    color: #f56c6c;

    &:hover {
      background-color: #f56c6c;
      border-color: #f56c6c;
      color: #fff;
    }
  }
}

.empty-canvas {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 300px;
  border: 2px dashed var(--el-border-color);
  border-radius: 4px;
  color: var(--el-text-color-secondary);
}

// 栅格布局样式
.grid-wrapper {
  // 栅格布局容器不需要额外的内边距
  padding: 4px;
}

// 描述列表样式
.descriptions-wrapper {
  padding: 4px;

  .el-descriptions {
    width: 100%;
  }
}

.grid-layout {
  width: 100%;
}

.grid-column {
  border: 1px dashed var(--el-border-color-lighter);
  transition: all 0.3s;

  &:hover {
    border-color: var(--el-border-color);

    .grid-column-header {
      opacity: 1;
    }
  }

  &.grid-column-active {
    border-color: var(--el-color-primary);
    background-color: var(--el-color-primary-light-9);

    .grid-column-header {
      opacity: 1;
    }
  }
}

.grid-column-content {
  height: 100%;
  display: flex;
  flex-direction: column;
  position: relative;
}

.grid-column-header {
  display: flex;
  justify-content: flex-end;
  align-items: center;
  padding: 4px 8px;
  position: absolute;
  bottom: 0;
  right: 0;
  z-index: 10;
  opacity: 0;
  transition: opacity 0.3s ease;
}

.grid-column-actions {
  display: flex;
  gap: 4px;

  .el-button {
    width: 20px;
    height: 20px;
    padding: 0;

    .el-icon {
      font-size: 12px;
    }
  }
}

.grid-column-drop-zone {
  flex: 1;
  // padding: 8px;
  position: relative;
}

.grid-column-empty {
  display: flex;
  align-items: center;
  justify-content: center;
  min-height: 40px;
  color: #c0c4cc;
  font-size: 12px;
}

.grid-child-item {
  position: relative;
  // margin-bottom: 8px;
  padding: 8px;
  border: 1px dashed transparent;
  border-radius: 4px;
  transition: all 0.3s;

  &:hover {
    border-color: #c0c4cc;
  }

  &.active {
    border-color: #409eff;
    background-color: #ecf5ff;
  }
}

.child-item-actions {
  position: absolute;
  top: 4px;
  right: 4px;

  .el-button {
    width: 20px;
    height: 20px;
    padding: 0;
  }
}
</style>
